package controllers

import (
	"net/http"
	"encoding/json"
	"git.oschina.net/YPTArch/processcache/sys/logs"
	"git.oschina.net/YPTArch/processcache/models"
	"io/ioutil"
	"strconv"
)



const (
	USER = "user:"
)

//用户登录
func Login(w http.ResponseWriter, r *http.Request) {
	logs.Logger.Debug("success in login")

	var result models.Result
	data, err := ioutil.ReadAll(r.Body)
	if err != nil {
		result = models.Result{Code:models.Unauthorized, Msg:"登录读取请求失败！", Data:""}
	}

	err = loginHandler(data)
	if err != nil {
		result = models.Result{Code:models.Unauthorized, Msg:"登录处理失败！", Data:""}
	}else {
		result = models.Result{Code:models.Ok, Msg:"登录成功！", Data:""}
	}

	re, err := json.Marshal(result)
	if err != nil {
		logs.Logger.Error(err.Error())
		w.Write([]byte(models.ServerErr))
	}

	w.Write(re)
}

func loginHandler(data []byte) (err error)   {

	//------解析部分-----
	var tokenRequest models.TokenRequest
	err = json.Unmarshal(data, &tokenRequest)
	if err != nil {
		logs.Logger.Error("login umarshall user err:"+err.Error())
		return
	}

	//存入redis中字段
	authUser := map[string]string{
		"Access":tokenRequest.Access,
		"AccessCreateAt":strconv.FormatInt(tokenRequest.AccessCreateAt, 10),
		"AccessExpiresIn":strconv.Itoa(tokenRequest.AccessExpiresIn),
		"UserId":tokenRequest.User.UserId,
		"UserPwd":tokenRequest.User.UserPwd,
		"UserName":tokenRequest.User.UserName,
		"UserPhone":tokenRequest.User.UserPhone,
		"UserEmail":tokenRequest.User.UserEmail,
	}


	return save(USER + tokenRequest.User.UserId,  authUser, tokenRequest.AccessExpiresIn)
}


//保存用户
func save(name string, authUser map[string]string, expiration int) error {

	//保存
	err := models.Save(name, authUser)
	if err != nil {
		logs.Logger.Error("Save err:" + err.Error())
		return err
	}

	//增加过期时间
	err = models.Delay(name, expiration)
	if err != nil {
		logs.Logger.Error("SetExpire err:" + err.Error())
		return err
	}

	return nil
}
